
import 'package:flutter/material.dart';
import 'package:flutter_1911/dao/SeachDao.dart';
import 'package:flutter_1911/pages/SpeakPage.dart';
import 'package:flutter_1911/pages/home_page.dart';
import 'package:flutter_1911/widget/webview.dart';
import '../model/seach_model.dart';
import '../until/nav_until.dart';
import '../widget/SearchBar.dart.';
//查找的类型
const TYPES = [
  'channelgroup',
  'gs',
  'plane',
  'train',
  'cruise',
  'district',
  'food',
  'hotel',
  'huodong',
  'shop',
  'sight',
  'ticket',
  'travelgroup'
];
//查找的路径
const URL =
    'https://m.ctrip.com/restapi/h5api/globalsearch/search?source=mobileweb&action=mobileweb&keyword=';

class ClassificationPage extends StatefulWidget {
  final bool? hideLeft;
  final String searchUrl;
  final String? keyword;
  final String? hint;

  const ClassificationPage(
      {Key? key, this.hideLeft, this.searchUrl = URL, this.keyword, this.hint})
      : super(key: key);

  @override
  _ClassificationPage createState() => _ClassificationPage();
}
class _ClassificationPage extends State<ClassificationPage> {
  SearchModel? searchModel;
  String? keyword;

  @override
  void initState() {
    if (widget.keyword != null) {
      _onTextChange(widget.keyword!);
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          _apptitle(),
          MediaQuery.removePadding(
              removeTop: true,
              context: context,
              child: Expanded(
                flex: 1,
                child: ListView.builder(
                    itemCount: searchModel?.data?.length ?? 0,
                    itemBuilder: (BuildContext context, int position) {
                      return _item(position);
                    }),
              )),

        ],
      ),
    );
  }

  //判断是否输入了搜索的内容
  _onTextChange(String text) {
    keyword = text;
    //判断输入文字的长度 如果为空输入框内容就为null
    if (text.length == 0) {
      setState(() {
        searchModel = null;
      });
      return;
    }
    //输入的文字 搜索到的内容 url
    String url=  '${(HomePage.configModel?.searchUrl ?? widget.searchUrl)}$text';
    SearchDao.fetch(url,text).then((SearchModel model){
      //判断它有没有
     if(model.keyword== keyword){
       setState(() {
         searchModel =model;
       });
     }
    }).catchError((e){
      print(e);
    });
  }
  //搜索页面的顶部搜素框
  _apptitle() {
    return Column(
      children: <Widget>[
        Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              //AppBar渐变遮罩背景
              colors: [Color(0x68888800), Colors.transparent],

              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          child: Container(
              padding: const EdgeInsets.only(top: 25),
              height: 80,
              decoration: const BoxDecoration(color: Colors.white),
              child: SearchBar(
                hideletf: widget.hideLeft,
                defaultText: widget.keyword,
                hint: widget.hint,
                speakClick: _jumpToSpeak,
                // 右边返回按钮
                rightButtonClick: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                },
                //左边的返回按钮
                leftButtonClick: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                  Navigator.pop(context);
                },
                //搜索框
                onChanged: _onTextChange,
              )),
        )
      ],
    );
  }

  _jumpToSpeak() {
    //点击进行跳转语言识别界面
    NavigatorUtil.push(context, SpeakPage());
  }

  _item(int position) {
    //判断搜索的有没有 searchModel 为空 或者searchModel的数据为空 就不显示
    if (searchModel == null || searchModel?.data == null) return null;

    Search item = searchModel!.data![position];
    return GestureDetector(
      onTap: () {
        NavigatorUtil.push(
            context,
            HiWebView(
              url: item.url!,
              title: '详情',
            ));
      },
      child: Container(
        padding: const EdgeInsets.all(10),
        decoration: const BoxDecoration(
            border: Border(bottom: BorderSide(width: 0.3, color: Colors.grey))),
        child: Row(
          children: <Widget>[
            Container(
              margin: const EdgeInsets.all(1),
              // child: Image(
              //     height: 26,
              //     width: 26,
              //     image: AssetImage(_typeImage(item.type))),
            ),
            Column(
              children: <Widget>[
                Container(
                  width: 300,
                  child: _title(item),
                ),
                Container(
                    width: 300,
                    margin: const EdgeInsets.only(top: 5),
                    child: _Title(item))
              ],
            )
          ],
        ),
      ),
    );
  }

  //展示搜索列表类型的图片
  _typeImage(String? type) {
    if (type == null) return 'images/type_travelgroup.png';
    String path = 'travelgroup';
    for (final val in TYPES) {
      if (type.contains(val)) {
        path = val;
        break;
      }
    }
    return 'images/type_$path.png';
  }
  //获得搜索内容的文字
  _Title(Search item) {
    return RichText(
      text: TextSpan(children: <TextSpan>[
        TextSpan(
          text: item.price ?? '',
          style: const TextStyle(fontSize: 15, color: Colors.orange),
        ),
        TextSpan(
          text: ' ${item.star ?? ''}',
          style: const TextStyle(fontSize: 10, color: Colors.grey),
        )
      ]),
    );
  }

  _keywordTextSpans(String? word, String keyword) {
    List<TextSpan> spans = [];
    if (word == null || word.length == 0) return spans;
    //搜索关键字高亮忽略大小写
    String wordL = word.toLowerCase(),
        keywordL = keyword.toLowerCase();
    List<String> arr = wordL.split(keywordL);
    TextStyle normalStyle = const TextStyle(fontSize: 16, color: Colors.black87);
    TextStyle keywordStyle = const TextStyle(fontSize: 16, color: Colors.orange);
    //'wordwoc'.split('w') -> [, ord, oc] @https://www.tutorialspoint.com/tpcg.php?p=wcpcUA
    int preIndex = 0;
    for (int i = 0; i < arr.length; i++) {
      if (i != 0) {
        //搜索关键字忽略大小写
        preIndex = wordL.indexOf(keywordL, preIndex);
        spans.add(TextSpan(
            text: word.substring(preIndex, preIndex + keyword.length),
            style: keywordStyle));
      }
      String val = arr[i];
      if (val != null && val.length > 0) {
        spans.add(TextSpan(text: val, style: normalStyle));
      }
    }
    return spans;
  }

  _title(Search item) {
    if (item == null) {
      return null;
    }
    List<TextSpan> spans = [];
    spans.addAll(_keywordTextSpans(item.word,searchModel!.keyword!));
    spans.add(TextSpan(
        text: ' ${item.districtname ?? ''}${item.zonename ?? ''}',
        style: const TextStyle(fontSize: 16, color: Colors.grey)));
    return RichText(text: TextSpan(children: spans));
  }
}